package org.sean.framework.canary.loadbalancer.predicate;

import org.sean.framework.canary.core.CanaryProperties;
import org.sean.framework.canary.core.CanaryUtils;
import org.sean.framework.canary.loadbalancer.CanaryPredicate;
import org.sean.framework.util.ObjectUtil;
import org.sean.framework.util.StringUtil;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.http.HttpHeaders;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 选择默认版本
 *
 * @author xielei
 */
public class ServerPredicate extends CanaryPredicate {
    private static Map<String, String> defaultServers = new HashMap<>();

    /**
     * 设置默认服务对应的label
     *
     * @param servers servers
     */
    public static void setServers(Set<CanaryProperties.Server> servers) {
        if (ObjectUtil.isNotEmpty(servers)) {
            servers.forEach(server -> defaultServers.put(server.getName(), server.getLabel()));
        }
    }

    public static void reset() {
        defaultServers.clear();
    }

    @Override
    public boolean getSelector(ServiceInstance server, HttpHeaders headers) {
        boolean result = false;
        String serverName = server.getServiceId();
        String serverLabel = CanaryUtils.getServerLabel(server);
        String ruleLabel = "";
        if (ObjectUtil.isNotEmpty(defaultServers)) {
            ruleLabel = defaultServers.get(serverName);
            // 服务单独配置label
            if (StringUtil.isNotEmpty(ruleLabel) && ruleLabel.equals(serverLabel)) {
                result = true;
            }
        }
        logger.debug("[{}] : {} -label : [{}] -- rule label : [{}] -- match result : [{}]",
                serverName, server.getUri(), serverLabel, ruleLabel, result);
        return result;
    }
}
